package net.woggle.shackbrowse;

import java.lang.reflect.Method;

import net.woggle.CustomClickableSpan;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.view.WindowManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class CustomURLSpan extends CustomClickableSpan {
	private String href;

	public CustomURLSpan(String href) {
		// TODO Auto-generated constructor stub
		super();
		this.href = href;
	}
	public static Dialog dialog;
	private static WebView _wb;
	
	public String getURL()
	{
		return href;
	}
	
	@Override
	public void onLongClick (View v)
	{
		final View view = v;
		final SherlockFragmentActivity activ = ((SherlockFragmentActivity)v.getContext());
		activ.runOnUiThread(new Runnable(){
    		@Override public void run()
    		{
    			AlertDialog.Builder builder = new AlertDialog.Builder(activ);
    			builder.setTitle("Choose Link Action");
    	        final CharSequence[] items = { "Copy URL","Open Externally", "Open in popup browser"};
    	        builder.setItems(items, new DialogInterface.OnClickListener() {
    	            public void onClick(DialogInterface dialog, int item) {
    	                if (item == 0)
    	                {
    	                	ClipboardManager clipboard = (ClipboardManager)activ.getSystemService(Activity.CLIPBOARD_SERVICE);
    	                	clipboard.setText(href);
    	                	Toast.makeText(activ, href, Toast.LENGTH_SHORT).show();
    	                }
    	                if (item == 1)
    	                {
    	                	Intent i = new Intent(Intent.ACTION_VIEW, 
    	             		       Uri.parse(href));
    	             		activ.startActivity(i);
    	                }
    	                if (item == 2)
    	                {
    	                	openDialogBrowser(view.getContext(), href);
    	                }
    	                }});
    	        AlertDialog alert = builder.create();
    	        alert.setCanceledOnTouchOutside(true);
    	        alert.show();
    		}
		});
	}
	
	@Override
	public void onClick (View v) 
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(v.getContext());
        int _useBrowser = Integer.parseInt(prefs.getString("usePopupBrowser2", "0"));
        
        // see if we can address URL internally
        int newId = 0;
        if (
        	href.contains("://www.shacknews.com/chatty?id=")
        	|| href.contains("://shacknews.com/chatty?id=")
        	|| href.contains("://www.shacknews.com/laryn.x?id=")
        	|| href.contains("://shacknews.com/laryn.x?id=")
        	)
        {
        	Uri uri = Uri.parse(getURL());
        	try
        	{
        		newId = Integer.valueOf(uri.getQueryParameter("id").trim());
        	}
        	catch (NumberFormatException e) { Toast.makeText(v.getContext(), "Invalid URL, could not open thread internally", Toast.LENGTH_SHORT).show(); }
        }
        
        // fix youtube app not handling their own youtu.be url shortener
    	if (href.contains("youtu.be"))
    	{
        	String[] splt = href.split("youtu.be/");
        	if (splt.length > 1)
        	{
        		href = "http://www.youtube.com/watch?v=" + splt[1];
        	}
    	}	
        
    	if (newId > 0)
    	{
    		System.out.println("opening new thread: " + newId);     
    		Activity activ = (Activity)v.getContext();
            if (activ instanceof MainActivity)
            {
            	int currentPostId = ((MainActivity)v.getContext())._threadView._adapter.getItem(((MainActivity)v.getContext())._threadView._lastExpanded).getPostId();
            	((MainActivity)v.getContext()).addToThreadIdBackStack(currentPostId);
            	((MainActivity)v.getContext()).openThreadViewAndSelectWithBackStack(newId);
            }
            
    	}
        else if (((_useBrowser == 0) && (!href.contains("play.google"))) || ((_useBrowser == 1) && (!href.contains("youtu.be")) && (!href.contains("youtube")) && (!href.contains("play.google"))) || ((_useBrowser == 2) && (isImage(href))))
        {
        	openDialogBrowser(v.getContext(), href);
        }
        else
        {
        	Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(this.getURL()));
     		v.getContext().startActivity(i);
        }
	}
	
	public static void openDialogBrowser (Context con, String... hrefs)
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
        int _attemptZoom = Integer.parseInt(prefs.getString("browserImageZoom", "2"));
        
		LayoutInflater inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vi = inflater.inflate(R.layout.webview_dialog, null);
        String _href = hrefs[0];
        _href = _href.trim();
        final String url = _href;
        
        
        dialog = null;
        // new dialog
        Activity activ = (Activity)con;
        if (activ instanceof MainActivity)
        {
        	dialog = ((MainActivity)activ).dialogGetInstance();
        }
        
        
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(vi);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        
        // buttons
        ImageButton buttonopen = (ImageButton)vi.findViewById(R.id.button_open);
        buttonopen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Do something in response to button click
            	Intent i = new Intent(Intent.ACTION_VIEW, 
            		       Uri.parse(url));
            		v.getContext().startActivity(i);
            		dialog.cancel();
            }
        });
        
        ImageButton buttonoptions = (ImageButton)vi.findViewById(R.id.button_options);
        buttonoptions.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Do something in response to button click
        		Intent i = new Intent(v.getContext(), PreferenceView.class);
                i.putExtra("pscreenkey", "popupbrowser");
                v.getContext().startActivity(i);
            	dialog.cancel();
            }
        });
        
        ImageButton buttonclose = (ImageButton)vi.findViewById(R.id.button_close);
        buttonclose.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Do something in response to button click
            	dialog.cancel();
            }
        });
        
        ImageButton buttoncopy = (ImageButton)vi.findViewById(R.id.button_copy);
        buttoncopy.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	ClipboardManager clipboard = (ClipboardManager)v.getContext().getSystemService(Activity.CLIPBOARD_SERVICE);
            	clipboard.setText(url);
            	Toast.makeText(v.getContext(), url, Toast.LENGTH_SHORT).show();
            }
        });

        // calculate sizes
        Display display = ((WindowManager) con.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        display.getMetrics(displaymetrics);
        int width = (int) Math.floor(displaymetrics.widthPixels);// - (28 * (displaymetrics.xdpi / 160)));
        // px = dp * (dpi / 160) according to android docs. so to use dips, use formula
        int height = (int) Math.floor(displaymetrics.heightPixels);// - ( 110 * (displaymetrics.ydpi / 160) ));
        System.out.println("btnh:" + buttonclose.getHeight());

        // progress bar
        ProgressBar progress = (ProgressBar)vi.findViewById(R.id.progress_bar);
        progress.setTag("progressTag");
        progress.setVisibility(View.VISIBLE);
        progress.setIndeterminate(false);
        
        // webview
        final WebView wb = (WebView) vi.findViewById(R.id.webView); // new WebView(vi.getContext());
        wb.getSettings().setBuiltInZoomControls(true);
        wb.getSettings().setJavaScriptEnabled(true);
        wb.setBackgroundColor(0x00000000);
        
        wb.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)   
            {
            	ProgressBar pb = (ProgressBar)((View)view.getParent().getParent()).findViewWithTag("progressTag");
            	LinearLayout parent = (LinearLayout) pb.getParent();
            	LinearLayout inactive = (LinearLayout)((LinearLayout)parent.getParent()).getChildAt(0);
            	if (pb != null && progress < 100)
            	{
            		pb.setVisibility(View.VISIBLE);
            		parent.setVisibility(View.VISIBLE);
            		inactive.setVisibility(View.GONE);
            		pb.bringToFront();
            		pb.setProgress(progress);
            	}
            	
            	System.out.println("prog:" + progress);
            	if (progress >= 100)
            	{
            		if (pb != null)
            		{
            			inactive.setVisibility(View.VISIBLE);
                		parent.setVisibility(View.GONE);
            			pb.setVisibility(View.INVISIBLE);
            		}
            		view.setVisibility(View.VISIBLE);
            		pb.bringToFront();
            		
            	}
            	if (progress >= 50)
            	{
            		// way to tell if showing image or not
            		if (!view.getSettings().getUserAgentString().contentEquals("nothing"))
            			view.setBackgroundColor(Color.WHITE);
            	}
            }
        });
        
        wb.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view,String _href) { return false; } });
        
        wb.getSettings().setDefaultZoom(ZoomDensity.FAR);
        wb.getSettings().setUseWideViewPort(true);
        wb.getSettings().setLoadWithOverviewMode(true);
        //wb.setBackground(con.getResources().getDrawable(R.drawable.bg_app_ics));
        //wb.setBackgroundColor(con.getResources().getColor(R.color.webview_bg));
        
        // multi image
        if (hrefs.length > 1)
        {
        	String html = "<html><head><title>Images</title><style type='text/css'> body{ margin: 0; padding: 0 } </style></head><body>";
        	for (int i = hrefs.length -1; i >= 0; i--)
        	{
        		_href = imageUrlFixer(hrefs[i].trim());
        		if (isImage(_href))
        		{
        			if (_attemptZoom > 0)
        				html = html +"<img width=\""+(width * (.34 + (.20 * _attemptZoom)))+"\" src=\""+_href+"\" /><br />";
        			else
        				html = html +"<img src=\""+_href+"\" /><br />";
        		}
        	}
        	html = html +"</body></html>";
        	if (_attemptZoom > 0)
        		wb.getSettings().setUseWideViewPort(false);
        	wb.getSettings().setUserAgentString("nothing");
        	//wb.setBackground(con.getResources().getDrawable(R.drawable.bg_app_ics));
            // wb.setBackgroundColor(con.getResources().getColor(R.color.webview_bg));
        	wb.loadData(html, "text/html", null);
        }
        // check for images, we scale for them
        else if (isImage(_href))
        {
        	_href = imageUrlFixer(_href);
        	if (_attemptZoom > 0)
        		wb.getSettings().setUseWideViewPort(false);
        	wb.getSettings().setUserAgentString("nothing");
        	String data="<html><head><title>Image</title><style type='text/css'> body{ margin: 0; padding: 0 } </style></head>";
        	
        	if (_attemptZoom > 0)
        	{
	        	if (width < height)
	        		data=data+"<body><center><img width=\""+(width * (.34 + (.20 * _attemptZoom)))+"\" src=\""+_href+"\" /></center></body></html>";
	        	else
	        		data=data+"<body><center><img height=\""+(height * (.34 + (.20 * _attemptZoom)))+"\" src=\""+_href+"\" /></center></body></html>";
        	}
        	else
        		data=data+"<body><center><img src=\""+_href+"\" /></center></body></html>";

        	//wb.setBackground(con.getResources().getDrawable(R.drawable.bg_app_ics));
            // wb.setBackgroundColor(con.getResources().getColor(R.color.webview_bg));
        	wb.loadData(data, "text/html", null);
        }
        else
        {
            wb.loadUrl(_href);
        }
        wb.setTag("webview_tag");
       // wb.setVisibility(View.GONE);

        // parent layout
        /*
        LinearLayout linLayout = (LinearLayout)vi.findViewById(R.id.linLayoutWebView);
        linLayout.setLayoutParams(new LinearLayout.LayoutParams(width, height));
        linLayout.setTag("popupLinLayout");
        
        linLayout.addView(wb, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, height));
        */
     
        _wb = wb;
        
        // setup back button
        dialog.setOnKeyListener(new Dialog.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (_wb.canGoBack())
                    {
                    	_wb.goBack();
                    }
                    else
                    {
                    	arg0.cancel();
                    }
                    return true;
                }
                // this allows volume keys to still work
                return false;
            }
        });
        
        // show dialog
        dialog.show();
	}
	
	public static boolean isImage (String _href)
	{
		if (
				(
        		(_href.trim().substring(_href.length() - 4).contentEquals(".jpg"))
        	|| (_href.trim().substring(_href.length() - 4).contentEquals(".gif"))
        	|| (_href.trim().substring(_href.length() - 4).contentEquals(".png"))
        	|| (_href.trim().substring(_href.length() - 5).contentEquals(".jpeg"))
				)
        	
        	)
        {
			return true;
        }
		else
		{
			return false;
		}
	}
	
	public static String imageUrlFixer (String _href)
	{
		if (_href.contains("shackpics.com"))
        {
        	String[] splt = _href.split("shackpics.com");
        	if (splt[1] != null)
        	{
        		_href = "http://chattypics.com/" + splt[1];
        	}
        }
		if (_href.contains("chattypics.com/viewer.php?"))
        {
        	String[] splt = _href.split("=");
        	if (splt[1] != null)
        	{
        		_href = "http://chattypics.com/files/" + splt[1];
        	}
        }
        if (_href.contains("fukung.net/v/"))
        {
        	String[] splt = _href.split(".net/v");
        	if (splt[1] != null)
        	{
        		_href = "http://media.fukung.net/images/" + splt[1];
        	}
        }
        if (_href.contains("www.dropbox"))
        {
        	_href = _href + "?dl=1";
        }
        return _href;
	}
}
